<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        table,td{
            border: solid 1px black;
        }

        td{
            width: 30px;
            height: 30px;
            transition: all 0.3s;
        }

        td[state=open]{
            background-color: white;
        }

        td[state=close]{
            background-color: cyan;
        }

    </style>
</head>
<body>
    
</body>
<script>
    var rows = 5;
    var cols = 5;

    var table = document.createElement("table");
    document.body.appendChild(table);

    var tds = [];

    for(var i = 0;i<rows;i++){
        var tr = table.insertRow();
        for(var j = 0;j<cols;j++){
            var td = tr.insertCell();
            tds.push(td);
        }
    }


    function reset(){
        tds.forEach(function(td){
            if(Math.random()>0.5){
                td.setAttribute("state","open");
                
            }else{
                td.setAttribute("state","close");
            }
        });
    }

    reset();

    tds.forEach(function(td,i){
        td.ind = i;
        td.onclick = tdClick;
    });

    function tdClick(e){
        
        function changeColor(el){
            var st = el.getAttribute("state");
            el.setAttribute("state",st=="open"?"close":"open");
        }
        //自身
        changeColor(e.target);
        //上格
        if(e.target.ind>=cols){
            changeColor(tds[e.target.ind-cols]);
        }
        //下格
        if(e.target.ind<cols*(rows-1)){
            changeColor(tds[e.target.ind+cols]);
        }
        //左格
        if(e.target.ind%cols!=0){
            changeColor(tds[e.target.ind-1]);
        }
        //右格
        if((e.target.ind+1)%cols!=0){
            changeColor(tds[e.target.ind+1]);
        }
    }

</script>
</html>